<template>
  <el-dialog
    v-model="visible"
    :title="year + '年事件'"
    @close="handleClose"
  >
    <el-form
      :model="formData"
      label-width="80px"
    >
      <el-form-item label="描述" required>
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="类型">
        <el-select v-model="formData.type" clearable>
          <el-option
            v-for="(item, index) in eventTypeData"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button
          v-if="isEditing"
          type="danger"
          @click="handleDelete"
        >
          删除
        </el-button>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">
          确认
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'

import { eventTypeData } from './data'

const props = defineProps({
  year: {
    type: Number,
    default: 0
  },
  event: {
    type: Object,
    default: () => {}
  },
  isEditing: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['save', 'delete', 'close'])

const visible = defineModel()

const formData = reactive({
  description: '',
  type: ''
})

watch(() => props.event, (newVal) => {
  formData.description = newVal.description
  formData.type = newVal.type
}, { deep: true })

const handleSubmit = () => {
  if (!formData.description.trim()) {
    ElMessage.warning('请输入事件描述')
    return
  }

  emit('save', {
    year: props.year,
    event: { ...formData }
  })
  formData.description = ''
  formData.type = ''
}

const handleDelete = () => {
  emit('delete')
}

const handleClose = () => {
  emit('close')
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
